package com.lyl.mallcloud.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyl.mallcloud.config.Result;
import com.lyl.mallcloud.mapper.UsersMapper;
import com.lyl.mallcloud.pojo.Users;
import com.lyl.mallcloud.service.IUsersService;
import com.lyl.mallcloud.utils.AliOssUtil;
import com.lyl.mallcloud.utils.ExcelUtils;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author liyunlong
 * @since 2024-05-10
 */
@Controller
@Slf4j
public class UsersController {

    @Autowired
    IUsersService usersService;

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    private AliOssUtil aliOssUtil;

    /***
     * @Description: 会员信息的分页展示
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @RequestMapping("/user/List")
    public String userList(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "4") Integer pageSize,
                           Model model, HttpSession session) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Users> users = usersMapper.selectList(null);
            PageInfo<Users> pageInfo = new PageInfo<>(users);
            int pages = pageInfo.getPages();
            List<Users> userItemList = pageInfo.getList();
            model.addAttribute("currentPage", pageNum);
            model.addAttribute("pages", pages);
            model.addAttribute("userItemList", userItemList);
            model.addAttribute("userName", session.getAttribute("userName"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("会员管理");
        return "/user/List";
    }

    /***
     * @Description: 查看会员信息
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @GetMapping("/info")
    public String info(@RequestParam(value = "id") Long id, Model model, HttpSession session) {
        Users user = usersService.findById(id);
        model.addAttribute("user", user);
        // session.setAttribute("userName", user.getUsername());
        log.info("查看用户信息：{}", user.getUsername());
        return "/user/Info";
    }

    /***
     * @Description: 删除会员
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @GetMapping("/delete")
    public String delete(@RequestParam(value = "id") Long id) {
        usersMapper.deleteById(id);
        log.info("删除用户信息：{}", id);
        return "redirect:/user/List";
    }

    /***
     * @Description: 批量删除会员
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @DeleteMapping("/deleteUserBatch")
    public ResponseEntity<?> deleteUserBatch(@RequestParam("ids") List<String> ids) {
        try {
            usersMapper.deleteBatchIds(ids);
            log.info("批量删除会员信息：{}", ids);
            return ResponseEntity.ok().body("批量删除会员成功");
        } catch (Exception e) {
            log.info("批量删除会员信息失败!");
            return ResponseEntity.status(500).body(e.getMessage());
        }
    }

    /***
     * @Description: 查看会员信息
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @GetMapping("/getById")
    public ResponseEntity<Users> getUserById(@RequestParam("id") Long id) {
        Users user = usersService.getById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(user);
    }

    /***
     * @Description: 保存会员信息
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @PostMapping("/users/save")
    @ResponseBody
    public Result createUser(@RequestBody Users userData) {
        usersService.save(userData);
        return Result.success();
    }

    @PostMapping("/users/get/{userId}")
    @ResponseBody
    public Result getUserById2(@PathVariable("userId") Long userId) {
        Users user = usersService.getById(userId);
        return Result.success(user);
    }

    /***
     * @Description: 添加会员页面
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @GetMapping("/user/AddUser")
    public String productDataView1(Model model, HttpSession session) {
        model.addAttribute("userName", session.getAttribute("userName"));
        return "/user/AddUser";
    }
    /***
     * @Description: 新增会员
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */

    @PostMapping("/user/addUser")
    public String addUser(
            @RequestParam("username") String username,
            @RequestParam("age") Integer age,
            @RequestParam("mobile") String mobile,
            @RequestParam("email") String email,
            @RequestParam("address") String address,
            @RequestParam("description") String description,
            @RequestParam(value = "avatar", required = false) MultipartFile avatar,
            RedirectAttributes redirectAttributes, HttpSession session) {
        Users users = new Users();
        users.setUsername(username);
        users.setAge(age);
        users.setMobile(mobile);
        users.setEmail(email);
        users.setAddress(address);
        users.setDescription(description);
        // 检查 avatar 是否为空
        if (avatar != null && !avatar.isEmpty()) {
            try {
                // 原始文件名
                String originalFilename = avatar.getOriginalFilename();
                // 截取文件名后缀  xxx.png
                assert originalFilename != null;
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                // 构造新文件名称
                String objectName = UUID.randomUUID() + extension;
                // 返回文件请求路径
                String filePath = aliOssUtil.upload(avatar.getBytes(), objectName);
                users.setAvatar(filePath);
            } catch (IOException e) {
                log.error("文件上传失败");
                e.printStackTrace();
            }
        }
        boolean save = usersService.save(users);

        if (save) {
            redirectAttributes.addFlashAttribute("message", "添加成功");
            log.info("新增用户：{}", users.getUsername());
            return "redirect:/user/List";
        } else {
            redirectAttributes.addFlashAttribute("message", "添加失败");
            log.info("新增用户失败");
            return "redirect:/user/AddUser";
        }
    }

    @GetMapping("/InInfo")
    public String userInfo(@RequestParam(value = "name") String name, Model model, HttpSession session) {
        session.setAttribute("userName", name);
        Users user = usersService.findByUserName(name);
        model.addAttribute("user", user);
        log.info("查看用户：{}信息", user.getUsername());
        return "/user/Info";
    }

    /***
     * @Description: 编辑会员信息前信息的回显
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @GetMapping("/editUser")
    public String userEdit(@RequestParam(value = "id") Long id, Model model, HttpSession session) {
        Users users = usersMapper.selectById(id);
        model.addAttribute("users", users);
        model.addAttribute("userName", session.getAttribute("userName"));
        log.info("编辑用户：{}信息", users.getUsername());
        return "/user/EditUser";
    }

    /***
     * @Description: 更新操作
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @PostMapping("/updateUser")
    public String updateUser(
            @RequestParam("userId") Long userId,
            @RequestParam("username") String username,
            @RequestParam("age") Integer age,
            @RequestParam("mobile") String mobile,
            @RequestParam("email") String email,
            @RequestParam("address") String address,
            @RequestParam("description") String description,
            @RequestParam(value = "avatar", required = false) MultipartFile avatar,
            RedirectAttributes redirectAttributes, Model model) {
        Users user = new Users();
        user.setId(Math.toIntExact(userId));
        user.setUsername(username);
        user.setAge(age);
        user.setMobile(mobile);
        user.setEmail(email);
        user.setAddress(address);
        user.setDescription(description);
        // 检查 imageUrl 是否为空
        if (avatar != null && !avatar.isEmpty()) {
            try {
                // 原始文件名
                String originalFilename = avatar.getOriginalFilename();
                // 截取文件名后缀  xxx.png
                assert originalFilename != null;
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                // 构造新文件名称
                String objectName = UUID.randomUUID() + extension;
                // 返回文件请求路径
                String filePath = aliOssUtil.upload(avatar.getBytes(), objectName);
                user.setAvatar(filePath);
            } catch (IOException e) {
                log.error("会员照片上传失败");
                e.printStackTrace();
            }
        }
        usersService.updateById(user);
        redirectAttributes.addFlashAttribute("message", "修改成功");
        log.info("修改会员信息成功");
        return "redirect:/user/List";

    }

    /***
     * @Description: 导出会员信息
     * @Author: Liyunlong
     * @Date: 2024/5/12
     */
    @GetMapping("/exportUser")
    public void exportUser(HttpServletResponse response) throws IOException {
        String excelName = "会员信息";
        List<Users> list = usersMapper.selectList(null);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String fileName = excelName + now.format(formatter);
        log.info("导出会员信息，文件名：{}", fileName);
        ExcelUtils.exportExcel(new ArrayList<>(list), excelName, excelName, Users.class, fileName, response);
    }
}